<?php
/**
 * Created by PhpStorm.
 * User: hpp
 * Date: 2019/12/18
 * Time: 17:13
 */

namespace api\department\controller;


use api\common\model\RlApplyDelayModel;
use api\common\model\RlCompanyModel;
use api\common\model\RlEtAzdModel;
use api\common\model\RlEtAzsModel;
use api\common\model\RlEtCompanyModel;
use api\common\model\RlEtCustomerModel;
use api\common\model\RlHiseServiceProjectModel;
use api\common\model\RlZsmsUserQueryModel;
use cmf\controller\PublicController;
use think\Db;
use think\Validate;
use api\common\service\MsgService;
use api\common\service\FunctionService;
/**
 * 分公司相关控制器
 */
class CompanyController extends PublicController
{
    protected $auth = '*';

    protected $status = [
        '进行中' => 1,
        '已完成' => 2,
        '已延期' => 3,
    ];

    protected $gw = [
        0 => '经销商',  1 => '经销商销售顾问', 2 => '经销商信息员', 3 => '分公司服务经理', 4 => '分公司服务助理', 5 => '分公司服务工程师', 6 => '分公司销售工程师', 7 => '大区总监', 8 => '安装结算模块管理员', 9 => '客户服务部部长', 10 => '客服部品牌负责人',
    ];

    /**
     * 安装单状态-new
     * @var array
     */
    protected $install_status_new = [
        0 => '未进场',
        1 => '已进场',
        2 => '隐蔽施工中',
        3 => '隐蔽施工已结束',
        4 => '调试',
        5 => '运行',
        'X' => '作废',
    ];


    public $dispatch =[
        '待接收'=>1,
        '已接受'=>2,
        '已拒收'=>3,
    ];
    protected $kqshzt_type_status = [
        0 => '',//不跨区
        1 => '初始',
        2 => '提交',
       3 => '驳回',
        4 => '接受',
    ];
    protected $kqshzt_status = [
        '不跨区' => 0,
        '初始' => 1,
        '提交' => 2,
        '驳回'   => 3,
        '接受'   => 4,
    ];

    public function _initialize()
    {
        $this->RlZsmsUserQueryModel = new RlZsmsUserQueryModel;
        $this->RlEtCustomerModel = new RlEtCustomerModel;
    }

    /**
     * 选择经销商数据/安装队
     * @api http://xxxx.com/api/department/company/getcompany  get
     * @param type 2经销商 3安装队
     * @param jxsbm type=3的时候传
     */
    public function getcompany(){
        $type = $this->request->param('type');
       $fgscode = $this->user['bm_code'];
        // $fgscode = 110;
        if (!in_array($type, [1,2,3])) {
            $this->error('查询信息错误');
        }
        if ($type == 1){
        }elseif ($type == 2){
            # 经销商
            $data = RlCompanyModel::getJxs($fgscode);
        }else{
            # 安装队
            $jxsbm = $this->request->param('jxsbm');
            $data = RlCompanyModel::getAzd($jxsbm);
        }
        $this->success('请求成功',$data);
    }

    //分公司查看待跨区和跨区待接收的单子
    public function kqitemlist()
    {
        $stra_kqshzt = $this->request->get('stra_kqshzt/d');
        $map['kqshzt'] = $stra_kqshzt;
        if($stra_kqshzt==1){
            $map['kqshzt'] = ['in','1,2,3'];
        }else{
            $map['kqshzt'] = ['in','2,4'];
            $map['zzdpdzt'] = ['<>',3];
        }
        $map['sfkq_bs'] = 1;
        
        $selectdata = $this->request->param();
        $funt = new FunctionService;
        $selectazd = $funt->selectazd($selectdata);
        $map = array_merge($selectazd,$map);
        $map1 = $map2 = $map;
        if($stra_kqshzt==1)
        {
            $map['qyfgs'] = $this->user['bm_code'];
        }else{
            $map['fwfgs'] = $this->user['bm_code'];
        }
        //排序
        $order = $this->request->param('order','');
        $orderwhere = '';
        if($order)
        {
            if($order=='asc')
            {
                $orderwhere = 'hise_service_project_id asc';
            }
            if($order=='desc')
            {
                $orderwhere = 'hise_service_project_id desc';
            }
        }
        if(!$orderwhere)
        {
            $orderwhere = 'hise_service_project_id desc';
        }
        $pege = input('param.pege');
        $limit = input('param.limit');
        $start = ($pege-1)*$limit;
  //      dump($map);
      /*  die;*/
        // 获取安装单列表信息
        $list = Db::table('cmf_rl_hise_service_project')
            ->where($map)
            ->order($orderwhere)
            ->limit($start,$limit)
            ->select()
            ->toArray();
//	dump($list);die;
        $provices = Db::name('rl_hise_area')->column('sf_name','sf_code');
        $citys = Db::name('rl_hise_dq_table')->column('dq_name','dq_code');
        $qxs = Db::name('rl_hise_qx_table')->column('qx_name','qx_code');
        // 遍历格式化数据等信息
        foreach ($list as $key => $val) {
            $list[$key]['yyaz_sj'] = $val['yyaz_sj'] ? date('Y-m-d', $val['yyaz_sj']) : '';
            $provice = $provices[$val['provice']];
            $city = $citys[$val['city']];
            $qx = $qxs[$val['qx']];
            $list[$key]['problem_num']  = Db::name('rl_inspect')->where('azd_id',$val['azd_id'])->where('is_problem',1)->where('inspect_status',2)->count();
            $list[$key]['address'] = $provice . $city . $qx . $val['address'];
            $list[$key]['gczt_name'] = $this->install_status_new[$val['gczt']];
            if($val['azd'])
            {
                $list[$key]['engineer_name'] = Db::name('rl_et_azd')->where('engineer_code', $val['azd'])->value('engineer_name');
            }else{
                $list[$key]['engineer_name'] = '';
            }
            $list[$key]['kqshzt_name'] = $this->kqshzt_type_status[$val['kqshzt']];
            unset($list[$key]['provice']);
            unset($list[$key]['city']);
            unset($list[$key]['qx']);
        }
        
        // 待派工
        $map2['kqshzt'] = ['in','1,2,3'];
        $map2['sfkq_bs'] = 1;
        $map2['qyfgs'] = $this->user['bm_code'];
        $data['count_2'] = $this->installationMountCount($map2);
        
        // 待接收
        $map3['kqshzt'] = ['in','2,4'];
        $map3['sfkq_bs'] = 1;
        $map3['fwfgs'] = $this->user['bm_code'];
        $map3['zzdpdzt'] = ['<>',3];
        $data['count_3'] = $this->installationMountCount($map3);
        // 安装队列表
        $data['list'] = $list;
        // 数据返回
        $this->success('操作成功！', $data);
    }
    /*显示金卡号占用情况*/
    public function occupy(){
        $vip_code=$this->request->param('vip_code');
        if($vip_code){
            //通过vip卡号查询订单
            $list = Db::table('cmf_rl_hise_service_project')->where('jkh',$vip_code)->select()->toArray();
            if($list){
                $this->success('操作成功！', $list);
            }
            $this->error('暂未查询到相关信息！', '');
        }
    }
    /*显示条码重复的占用情况*/
    public function occupy_Barcode(){
        $barcode=$this->request->param('barcode');
        $azd_id=Db::table('cmf_rl_hise_service_pro_inst_detail')->where('jqxlh',$barcode)->value('azd_id');
        $list = Db::table('cmf_rl_hise_service_project')->where('azd_id',$azd_id)->select()->toArray();
        if($list){
            $this->success('操作成功！', $list);
        }
        $this->error('暂未查询到相关信息！', '');
    }
    /**
     * 分公司--安装单列表   经销商编码查询
     * @api http://xxxx.com/api/department/company/installlist get
     * @param int    sfwc      2进行中 3已完成
     * @param int type 1分公司 2经销商
     *
     */

    /**
     * @api http://xxxx.com/api/department/company/report get
     */
    public function report(){
        $service_project_id = $this->request->param('service_project_id','');
        if(!$service_project_id)$this->error('参数错误');
        //多表引入查询方法
        $info = RlHiseServiceProjectModel::Where('hise_service_project_id',$service_project_id)->field('azd_id,yh_name,xb,sj_one,provice,city,qx,address,qyfgs,jxs
        ,azs,azd,fgsfwfzr,cplb,yyjc_sj,jkh,zjbxq,zybjbxq,jxsxsy,bz,pic_one,pic_two,wgsj')->find();
        $info['wgsj'] = date('Y-m-d',$info['wgsj']);
        if(!$info) $this->error('该用户不存在');
        if(empty($info['qx'])){
            $city = Db::name('rl_hise_dq_table')->where('dq_code',$info['city'])->field('dq_name')->select()['dq_name'];
            $provice = Db::name('rl_hise_area')->where('sf_code',$info['provice'])->field('sf_name')->find()['sf_name'];
            $info['address_detail'] = $provice.$city.$info['address'];
            $info['address'] = $provice.$city;
        }else{
            $xq = Db::name('rl_hise_qx_table')->where('qx_code',$info['qx'])->field('qx_name')->find()['qx_name'];
            $city = Db::name('rl_hise_dq_table')->where('dq_code',$info['city'])->field('dq_name')->find()['dq_name'];
            $provice = Db::name('rl_hise_area')->where('sf_code',$info['provice'])->field('sf_name')->find()['sf_name'];
            $info['address_detail'] = $provice.$city.$xq.$info['address'];
            $info['address'] = $provice.$city.$xq;
        }
        $info['jxs_name'] = RlEtCustomerModel::where('jxsbm',$info['jxs'])->field('jxs_mc')->find()['jxs_mc'];
        $info['azs_name'] = RlEtAzsModel::where('server_code',$info['azs'])->field('server_name')->find()['server_name'];
        $info['azd_name'] = RlEtAzdModel::where('engineer_code',$info['azd'])->field('engineer_name')->find()['engineer_name'];
        $info['fgs_name'] = Db::name('rl_company')->where('orgdept',$info['qyfgs'])->field('orgname')->find()['orgname'];
        $info['yyjc_sj']  = date('Y-m-d', $info['yyjc_sj']);
        $info['jxs_name'] = RlEtCustomerModel::where('jxsbm',$info['jxs'])->field('jxs_mc')->find()['jxs_mc'];
        $prefix = 'cmf_';
        $join = [
            ["{$prefix}rl_node node", 'node.node_id = pro.azjd'],
        ];
        $list = Db::name('rl_hise_service_pro_process')->alias('pro')
            ->join($join)
            ->where('pro.gc_azdid',$info['azd_id'])->order('node.sort desc')
            ->field('pro.jdqrsj,pro.cplp,pro.azjd,pro.tp_one,pro.tp_two,pro.tp_there,node.node_name')
            ->select();
        $data['info'] = $info;
        $data['node_list'] = $list;
        $this->success('请求成功',$data);
    }

    /** 
     * 经销商申请延迟交付
     * @api http://xxxx.com/api/department/company/applydelay get
     * @param int service_project_id  按转单id
     */
    public function applydelay(){
        $service_project_id = $this->request->param('service_project_id');
        if(!$service_project_id)$this->error('请求失败','');
        $where['hise_service_project_id'] =  $service_project_id;
//        $ishas = RlApplyDelayModel::where($where)->where('status',0)->find();
//        if ($ishas) $this->error('正在申请中');
        $row  = RlHiseServiceProjectModel::where($where)->find()->toArray();
        if($row['gczt']==5){
		$this->error('安装单已运行，无法申请延期');
	}
        $data['jxsmc']  = RlEtCustomerModel::where('jxsbm',$row['jxs'] )->field('jxs_mc')->find()['jxs_mc'];
        $data['azd_id'] = $row['azd_id'];
        $data['jxsbm'] = $row['jxs'];
        $data['service_project_id'] = $service_project_id;
        $this->success('请求成功',$data);
    }
    /**
     * 提交延迟交付
     * @api http://xxxx.com/api/department/company/applysave post
     */
    public function applysave(){
        $azd_id = $this->request->param('azd_id');
        $id = $this->request->param('service_project_id');
        if(!$azd_id || !$id)$this->error('请求失败','');
        // 不能重复提交
        $ishas = RlApplyDelayModel::where(['status' => 0,'hise_service_project_id' => $id,'azd_id' => $azd_id])->find();
        if ($ishas) $this->error('请不要重复提交');
        $where['azd_id'] =  $azd_id;
        $res = RlHiseServiceProjectModel::where($where)->field('ycgcsfjsbs')->find()['ycgcsfjsbs'];

        if(!$res)$this->error('未满足条件不能提交','');
        $data['jxsmc'] = $this->request->param('jxsmc','');
        $data['jxsbm'] = $this->request->param('jxsbm','');
        $data['yqsqzq'] = $this->request->param('yqsqzq','');
        $data['yqsqzq']=intval($data['yqsqzq']);
        if(!$data['yqsqzq']){
            $this->error('请填写延期周期');
        }
        if($data['yqsqzq']>6){
            $this->error('延期周期不得大于6个月');
        }
        $data['img'] = $this->request->param('img','');
        if (!$data['img']){
            $this->error('请上传附件');
        }
        $data['azd_id'] = $azd_id;
        $data['hise_service_project_id'] = $id;
        $data['status']  =0;
        $res=RlApplyDelayModel::create($data);
        if(!$res){
            $this->error('无法添加申请数据，请联系管理员','');
        }
        RlHiseServiceProjectModel::where($where)->update(['is_apply_delay'=>1,'update_time'=>time()]);
        if(config('installsend4'))
              {
                // 引用发送验证码类：分公司售后信息员
                $msg_send = new MsgService();
                // 发送手机验证码
                $item = RlHiseServiceProjectModel::where($where)->find();
                $fwfgs = $item['fwfgs'];
                $azdId = $item['azd_id'];
                $jxs_name = RlEtCustomerModel::where('jxsbm',$item['jxs'])->find()['jxs_mc'];
                $jxs = RlZsmsUserQueryModel::Where('bm_code',$fwfgs)->where('gw',4)->where('status',1)->select()->toArray();
                foreach ($jxs as $key => $value) {
                    $phone = $value['mobilphone'];
                    $msgres = $msg_send->installsend4($azdId,$phone,$jxs_name);
                    if($msgres)
                    {
                        trace($phone.'||'.date('Y-m-d h:i:s',time()).'延时审核短信发送成功','info');
                    }else{
                        trace($phone.'||'.date('Y-m-d h:i:s',time()).'延时审核短信发送失败','info');
                    }
                }
                //分公司服务工程师
                $jxs = RlZsmsUserQueryModel::Where('bm_code',$item['fwfgs'])->where('user_name',$item['fgsfwfzr'])->where('gw',5)->where('status',1)->select()->toArray();
                foreach ($jxs as $key => $value) {
                    $phone = $value['mobilphone'];
                    $msgres = $msg_send->installsend4($azdId,$phone,$jxs_name);
                    if($msgres)
                    {
                        trace($phone.'||'.date('Y-m-d h:i:s',time()).'延时审核短信发送成功','info');
                    }else{
                        trace($phone.'||'.date('Y-m-d h:i:s',time()).'延时审核短信发送成功','info');
                    }
                }
                //分公司服务经理
                $jxs = RlZsmsUserQueryModel::Where('bm_code',$item['fwfgs'])->where('user_name',$item['fgsfwfzr'])->where('gw',3)->where('status',1)->select()->toArray();
                foreach ($jxs as $key => $value) {
                    $phone = $value['mobilphone'];
                    $msgres = $msg_send->installsend4($azdId,$phone,$jxs_name);
                    if($msgres)
                    {
                        trace($phone.'||'.date('Y-m-d h:i:s',time()).'延时审核短信发送成功','info');
                    }else{
                        trace($phone.'||'.date('Y-m-d h:i:s',time()).'延时审核短信发送成功','info');
                    }
                }
              }
        $this->success('申请成功','');
    }

    /**
     * 申请延期交付信息
     * @api http://xxxx.com/api/department/company/delayInfo get
     * @param hise_service_project_id  int       安装单主键ID
     * @param azd_id                   string    安装单编号
     */
    public function delayInfo(){
        $projectId = $this->request->get('hise_service_project_id',0);
        $azdId = $this->request->get('azd_id','');
        if (!$projectId || !$azdId){
            $this->error('参数不正确');
        }
        $project = RlHiseServiceProjectModel::where(['hise_service_project_id' => $projectId,'azd_id' => $azdId])->field('is_apply_delay')->find();
        if ($project['is_apply_delay'] != 1){
            $this->error('此工程未申请延迟交付');
        }
        $apply = Db::name('rl_apply_delay')->where(['azd_id' => $azdId,'status' => 0])->field('id as apply_id,jxsmc,yqsqzq,azd_id,img')->find();
        $this->success('操作成功',$apply);
    }

    /**
     * 审核申请延迟
     * @api http://xxxx.com/api/department/company/checkApply post
     * @param apply_id    int    申请id
     * @param azd_id      string  安装单编码
     * @param status      int     1通过   2不通过
     * @param content     string  驳回原因
     */
    public function checkApply(){
        $id = $this->request->post('apply_id',0);
        $azdId = $this->request->post('azd_id','');
        $status = $this->request->post('status');
        $content = $this->request->post('content');
        if (!$id || !$azdId || !in_array($status,[1,2])){
            $this->error('参数错误');
        }
        $info = RlApplyDelayModel::get(['id' => $id,'azd_id' => $azdId]);
        if ($info['status'] != 0){
            $this->error('已经审核');
        }
        $applyRes = RlApplyDelayModel::where(['id' => $id,'azd_id' => $azdId])->update(['status' => $status,'content' => $content]);
        if (!$applyRes) {
            $this->error('更新失败');
        }
        // 更新工程表
        if($status==1)
        {
             $res = RlHiseServiceProjectModel::where(['azd_id' => $azdId])->setInc('yqsqzq',$info['yqsqzq']);
        }
        if($status==2)
        {
            $res = RlHiseServiceProjectModel::where(['azd_id' => $azdId])->update(['is_apply_delay' => 0]);
        }
        if ($res === false){
            $this->error('更新失败2');
        }
        if($status==1)
        {
            $yqsq_bs=RlHiseServiceProjectModel::where(['azd_id' => $azdId])->value('yqsq_bs');
            //if($yqsq_bs==0){
                RlHiseServiceProjectModel::where(['azd_id' => $azdId])->update(['yqsq_bs'=>1,'update_time'=>time()]);
            //}
            if(config('installsend5'))
              {
                // 引用发送验证码类短信接收人：经销商
                $msg_send = new MsgService();
                // 发送手机验证码
                $jxsbm = RlApplyDelayModel::where(['id' => $id,'azd_id' => $azdId])->find()['jxsbm'];
                $jxs = RlZsmsUserQueryModel::Where('bm_code',$jxsbm)->where('gw',0)->where('status',1)->select()->toArray();
                  trace($azdId.'||'.date('Y-m-d H:i:s',time()).'审核通过短信发送成功---经销商数据：'.json_encode($jxs),'info');
                foreach ($jxs as $key => $value) {
                    $phone = $value['mobilphone'];
                    $msgres = $msg_send->installsend5($azdId,$phone);
                    if($msgres)
                    {
                        trace($phone.'||'.date('Y-m-d h:i:s',time()).'审核通过短信发送成功','info');
                    }else{
                        trace($phone.'||'.date('Y-m-d h:i:s',time()).'审核通过短信发送失败','info');
                    }
                }
              }
        }else{
            if(config('installsend6'))
              {
                // 引用发送验证码类短信接收人：经销商
                $msg_send = new MsgService();
                // 发送手机验证码
                $jxsbm = RlApplyDelayModel::where(['id' => $id,'azd_id' => $azdId])->find()['jxsbm'];
                $jxs = RlZsmsUserQueryModel::Where('bm_code',$jxsbm)->where('gw',0)->where('status',1)->select()->toArray();
                foreach ($jxs as $key => $value) {
                    $phone = $value['mobilphone'];
                    $msgres = $msg_send->installsend6($azdId,$phone);
                    if($msgres)
                    {
                        trace($phone.'||'.date('Y-m-d h:i:s',time()).'审核不通过短信发送成功','info');
                    }else{
                        trace($phone.'||'.date('Y-m-d h:i:s',time()).'审核不通过短信发送失败','info');
                    }
                }
              }
        }
        $this->success('操作成功',[]);
    }

    /**
     * 分公司--安装单状态对应数量
     */
    protected function installationMountCount($map)
    {
        // 获取安装单数量
        $count = Db::table('cmf_rl_hise_service_project')
            // ->alias('hise')
            // ->join('cmf_rl_et_azd azd','hise.azd = azd.engineer_code')
            ->where($map)
            ->count();
        return $count;
    }


    /**
     * 经销商通讯录
     * status
     */
    public function userlist()
    {
//        $bmcode = '2000860';
        $bmcode = $this->user['bm_code'];
        
        $where = [];
        $param = $this->request->param();
        if(isset($param['keyword']) && $param['keyword'])
        {

            $where['user_name'] = ['like','%'.$param['keyword'].'%'];
        }
        if(isset($param['mobilphone']) && $param['mobilphone'])
        {

            $where['mobilphone'] = ['like','%'.$param['mobilphone'].'%'];
        }
        if(isset($param['zyd_mc']) && $param['zyd_mc'])
        {

            $where['zyd_mc'] = ['like','%'.$param['zyd_mc'].'%'];
        }
        $a = $this->RlZsmsUserQueryModel->where('bm_code',$bmcode)->where('ignore',0)->where('status_sms','<>',2)->where($where)->column('zyd_mc');
        $zyd_mc = [];
        foreach($a as $k=>$v){
            if (!in_array($v,$zyd_mc)){
                $zyd_mc[]  = $v;
            }
        }
        $user = $this->RlZsmsUserQueryModel->where('bm_code',$bmcode)->where('ignore',0)->where('status_sms','<>',2)->where($where)->order('zyd_mc', 'desc')->field('zsms_user_query_id,user_id,user_name,gw,mobilphone,status,zyd_mc,gw_cp')->select()->toArray();
        $data = [];
        foreach ($zyd_mc as $key => $value) {
            $data[$key]['zyd_mc'] = $value;
            foreach ($user as $k => $v) {
                if($v['zyd_mc'] == $value)
                {
                    //经销商
                    $v['jxs_mc'] = $this->RlEtCustomerModel->where('jxsbm',$bmcode)->value('jxs_mc');
                    $v['gw'] = $this->gw[$v['gw_cp']];
                    $data[$key]['user'][] = $v;
                }
            }
        }
        $this->success("查询成功!",['data'=>$data]);
    }

    /**
     * @qpi http://xxxx.com/api/department/company/jxstxDetail
     * @param mobilphone
     */
    public function jxstxDetail(){
        $mobile = $this->request->param('mobilphone');
        if(!$mobile){
            $this->error('参数不正确');
        }
        $bmcode = $this->user['bm_code'];
        $info = RlZsmsUserQueryModel::where(['mobilphone' => $mobile])->where('ignore',0)->field('zsms_user_query_id,user_name,mobilphone,gw,zyd_mc,status')->find();
        if (!$info){
            $this->error('没有该条记录');
        }
        $info['gw'] =$this->gw[$info['gw']];
        $info['jxs_mc'] = $this->RlEtCustomerModel->where('jxsbm',$bmcode)->value('jxs_mc');
        $this->success('ok',$info);
    }

    /**
     * 分公司通讯录
     * @api http://xxxx.com/api/department/company/address
     * @param keyword 搜索
     */
    public function address(){
        $keyword = $this->request->get('keyword','');
        $user_name = $this->request->get('user_name','');
        $mobilphone = $this->request->get('mobilphone','');
        
        $where = [];
       if ($keyword){
           $map['jxs_mc|mobil'] = ['like',"%{$keyword}%"];
       }
       if(isset($user_name) && $user_name)
        {

            $where['user_name'] = ['like','%'.$user_name.'%'];
        }
        if(isset($mobilphone) && $mobilphone)
        {

            $where['mobilphone'] = ['like','%'.$mobilphone.'%'];
        }
        // todo
        $fgs = $this->user['bm_code'];
//        $fgs = 106;
        $alljxsbms = RlEtCompanyModel::where(['flag' => 1,'fgs' => $fgs])->column('jxsbm');
        $map['jxsbm'] = ['in', $alljxsbms];
        $alljxs = RlEtCustomerModel::where($map)->field('et_customer_id,jxsbm,jxs_mc')->select()->toArray();
        foreach ($alljxs as $key => $value) {
            $alljxs[$key]['smsuser'] = Db::table('cmf_rl_zsms_user_query')->where($where)->where('ignore',0)->where('jxs_code',$value['jxsbm'])->where('status_sms','<>',2)->select()->toArray();
        }
        $alljxs_new = [];
        if($where)
        {
            foreach ($alljxs as $key => $value) {
                if(!$alljxs[$key]['smsuser'])
                {
                    unset($alljxs[$key]);
                }else{
                   $alljxs_new[] =  $value;
                }
            }
        }else{
            $alljxs_new = $alljxs;
        }
        $this->success('操作成功',$alljxs_new);
    }


    /**
     * 大区通讯录
     * @api http://xxxx.com/api/department/company/daddress
     * @param keyword 搜索
     */
    public function daddress(){
        $keyword = $this->request->get('keyword','');
        $map = [];
        if(is_numeric($keyword)){
            // $map['mobil'] = ['like',"%{$keyword}%"];
        }else{
            $map['orgname'] = ['like',"%{$keyword}%"];
        }
        $dq_code = $this->user['bm_code'];
        
        $allfgs = Db::table('cmf_rl_company')->where('patent_id',$qx_code)->where($map)->select()->toArray();
        $this->success('操作成功',$allfgs);
    }

    /*
     *修改销售岗位为经销商
     * @api http://xxxx.com/api/department/company/updategw post
     * @param mobilphone  sms用户手机号
     * @param jxsbm             经销商编码
     * @param gw   1销售 0经销商
     */
    public function updategw()
    {
        $mobilphone = $this->request->post('mobilphone',0);
        $jxsbm = $this->request->post('jxsbm','');
        $gw = $this->request->post('gw');
        if (!$mobilphone || !$jxsbm || !in_array($gw,[0,1,2])){
            $this->error('参数错误');
        }
        $data['gw'] = $gw;
        $data['update_time'] = time();
        $res = Db::table('cmf_rl_zsms_user_query')->where('ignore',0)->where('jxs_code',$jxsbm)->where('mobilphone',$mobilphone)->update($data);
        if($res)
        {
            return json(['code'=>1,'msg'=>'修改成功']);
        }else{
            return json(['code'=>0,'msg'=>'修改失败']);
        }
    }

    /**
     * 通讯录详情--已废弃
     * @api http://xxxx.com/api/department/company/addressdetail
     * @param et_customer_id  经销商主键id
     * @param jxsbm             经销商编码
     */
    public function addressdetail(){
        // $id = $this->request->get('et_customer_id',0);
        // $jxsbm = $this->request->get('jxsbm','');
        // if (!$id || !$jxsbm){
        //     $this->error('参数不正确');
        // }
        // $info = RlEtCustomerModel::where(['et_customer_id' => $id,'jxsbm' => $jxsbm])->field('et_customer_id,jxsbm,jxs_mc,dj_flag')->find()->toArray();
        // $user = Db::table('cmf_rl_zsms_user_query')->where('jxs_code',$jxsbm)->where('ignore',0)->where('gw',0)->find();
        // $info['status'] = $user['status'];
        // $this->success('操作成功',$info);
        $data = $this->request->param();
        $user = $this->RlZsmsUserQueryModel->where('mobilphone',$data['mobilphone'])->where('ignore',0)->find();
        if(in_array($this->user['gw'], [0,1,2]))
        {
            $user['bm_mc'] = $this->RlEtCustomerModel->where('jxsbm',$this->user['bm_code'])->value('jxs_mc');
        }elseif(in_array($this->user['gw'], [3,4,5,6,7,8,9,10])){
            $user['bm_mc'] = RlCompanyModel::where('orgdept',$this->user['bm_code'])->value('orgname');
        }
        $this->success("查询成功!",['user'=>$user]);
    }

    /**
     * 更新是否冻结--已废弃
     * @api http://xxxx.com/api/department/company/update post
     * @param et_customer_id  经销商主键id
     * @param jxsbm             经销商编码
     * @param dj_flag   1没有 0冻结
     */
    public function update(){
        $id = $this->request->post('et_customer_id',0);
        $jxsbm = $this->request->post('jxsbm','');
        $status = $this->request->post('status');
        if (!$id || !$jxsbm || !in_array($status,[0,1,2])){
            $this->error('参数错误');
        }
        // $res = RlEtCustomerModel::where(['et_customer_id' => $id,'jxsbm' => $jxsbm])->update(['dj_flag' => $dj_flag]);
        $result = Db::table('cmf_rl_zsms_user_query')->where('ignore',0)->where('jxs_code',$jxsbm)->where('gw',0)->find();
        if($result)
        {
            $data['status'] = $status;
            $data['update_time'] = time();
            $res = Db::table('cmf_rl_zsms_user_query')->where('ignore',0)->where('jxs_code',$jxsbm)->where('gw',0)->update($data);
            if($res)
            {
                return json(['code'=>1,'msg'=>'修改成功']);
            }else{
                return json(['code'=>0,'msg'=>'修改失败']);
            }
        }
        return json(['code'=>0,'msg'=>'经销商没有老板信息']);
//        if (!$res){
//            $this->error('更新失败');
//        }
        // $this->success('更新成功');
    }



    /**
     * 获取随机编码
     * @param []
     * @return []
     * @date 2019/12/19 10:10 AM
     */
    public function nonceStr() {
        static $seed = array(0,1,2,3,4,5,6,7,8,9);
        $str = '';
        for($i=0;$i<8;$i++) {
            $rand = mt_rand(0,count($seed)-1);
            $temp = $seed[$rand];
            $str .= $temp;
            unset($seed[$rand]);
            $seed = array_values($seed);
        }
        $time = date('Ymd',time());
        return $time.$str;
    }




 /**
     * 分公司--安装单列表   经销商编码查询
     * @api http://xxxx.com/api/department/company/installlist get
     * @param int    sfwc      2进行中 3已完成
     * @param int type 1分公司 2经销商
     *
     */
    public function installlist_fuben88(){
        // 验证的规则
        $rule = [
            'sfwc' => 'require',
            'type' => 'require',
        ];
        // 错误的消息
        $msg = [
//            'engineer_code.require' => '工程师代码不存在',
            'sfwc.require' => '安装单状态不存在',
            'type.require' => '类型不存在',
        ];
        // 获取的数据
        $data = [
             //  'engineer_code' => $this->request->get('engineer_code'), // 获取工程师代码
            'sfwc' => $this->request->get('sfwc/d', '2'), // 获取安装单状态
            'type' => $this->request->get('type/d',1), // 类型 1分公司 2经销商
        ];
        // 直接传入验证规则
        $validate = Validate::make($rule)->message($msg);
        // 需要验证的数据
        $result = $validate->check($data);
        // 判断是否有验证错误
        if (!$result) {
            // 验证错误提示
            $this->error($validate->getError());
        }
        // 判断安装单状态
        if($data['sfwc'] == '2'){
            // 安装单状态
            $map['gczt'] = ['in','0,1,2,3,4'];
            $map['zzdpdzt'] = 3;
        } else {
            // 安装单状态 已完成
            $map['gczt'] = 5;
            $map['zzdpdzt'] = 3;
        }
        $selectdata = $this->request->param();
     
        $funt = new FunctionService;
        $selectazd = $funt->selectazd($selectdata);
       // $map = array_merge($map,$selectazd);
        $where='';
        if(isset($selectdata['is_apply_off'])){
            if($data['type']==1){
                //展示即将申请到期得安装单
                $where='gczt in (3,4) and ycgcwcsj+(2592000*(yqsqzq+9-1)) <'.time().'   and ycgcwcsj>0';
            }else{
                //展示即将申请到期得安装单
                $where='gczt in (3,4)  and ycgcwcsj>0';
            }

        }
        //排序
        $order = $this->request->param('order','');
        $orderwhere = '';
        if($order)
        {
            if($order=='asc')
            {
                $orderwhere = 'hise_service_project_id asc';
            }
            if($order=='desc')
            {
                $orderwhere = 'hise_service_project_id desc';
            }
        }
        if(!$orderwhere)
        {
            $orderwhere = 'hise_service_project_id desc';
        }
        // 分公司
        // $map['fwfgs'] = $this->user['bm_code'];
        // todo 修改成 $this->user['bm_code'];
        if($data['type'] == 1){
//            $map['fwfgs'] = 2007487;
            $map['fwfgs|qyfgs'] = $this->user['bm_code'];
        }elseif($data['type'] == 3){
            //根据大区获取分公司信息
            // $bm_codes = Db::table('cmf_rl_company')->where('patent_id',$this->user['bm_code'])->column('orgdept');
            // $bm_codes = implode(",", $bm_codes);
            // if(isset($selectazd['fwfgs']))
            // {
            //     $bm_codes = array_intersect($selectazd['fwfgs'],$bm_codes);
            // }
            // $map['fwfgs'] = ['in',$bm_codes];
        }else{
//            $map['jxs'] = 2007487;
            $map['jxs'] = $this->user['bm_code'];
        }
        //分页
           $pege = input('param.pege');
           if($pege==null){
               $pege=1;
           }
           $limit = input('param.limit');
           if($limit==null){
               $limit=10;
           }
           $start = ($pege-1)*$limit;

        $field = 'azd.engineer_name,hise.yh_name,hise.fgsfwfzr,hise.azd_id,hise.address,hise.provice,hise.city,hise.qx,hise.yyaz_sj,hise.gczt,hise.jxsxsy,hise.hise_service_project_id,hise.yqsqzq,hise.is_apply_delay';

        // 获取安装单列表信息
        $list = Db::table('cmf_rl_hise_service_project')
            ->where($map)
            ->where($where)
            ->where(function($list)use($selectdata,$start,$limit){
                if(isset($selectdata['start_time']) && isset($selectdata['end_time'])){

                 $list->whereOr('ycgcwcsj','between',[strtotime(getMsecToMescdate($selectdata['start_time'])),strtotime(getMsecToMescdate($selectdata['end_time']))]);
                }
             foreach($selectdata as $k=>$v){
                 switch ($k){
                     case 'yh_name':
                         $list->whereOr('yh_name','like','%'.$selectdata['yh_name'].'%');
                         break;
                     case 'azd_id':
                         $list->whereOr('azd_id','like','%'.$selectdata['azd_id'].'%');
                         break;
                     case 'sj_one':
                         $list->whereOr('sj_one','like','%'.$selectdata['sj_one'].'%');
                         break;
                     case 'address':
                         $list->whereOr('address','like','%'.$selectdata['address'].'%');
                         break;
                     case 'jxsxsy':
                         $list->whereOr('jxsxsy','like','%'.$selectdata['jxsxsy'].'%');
                         break;
                     case 'jxs_mc':
                         $jxsbm = Db::name('rl_et_customer')->where('jxs_mc','like','%'.$selectdata['jxs_mc'].'%')->column('jxsbm');
                         $list->whereOr('jxs','in',$jxsbm);
                         break;
                     case 'gczt':
                         $list->whereOr('gczt',$selectdata['gczt']);
                         break;
                     case 'sfxjbs':
                         $list->whereOr('sfxjbs',$selectdata['sfxjbs']);
                         break;
                     case 'is_problem':
                         $azd_id = Db::name('rl_inspect')->where('is_problem',1)->where('inspect_status',2)->column('azd_id');
                         $list->whereOr('azd_id','in',$azd_id);
                         break;
                         //申请延期标识
                     case 'is_apply_delay':
                         $list->whereOr('is_apply_delay',$selectdata['is_apply_delay']);
                         break;
                     default:
                         break;
                 }
             }
            })
            ->order($orderwhere)
            ->limit($start,$limit)
            ->select()
            ->toArray();
    //dump(Db::table('cmf_rl_hise_service_project')->getLastsql());die;
  if(isset($selectdata['is_apply_off'])){
             if($data['type']==1) {
                  if($pege>1){
                 $list=[];
             }
                $list = Db::table('cmf_rl_hise_service_project')
                  //  ->join('cmf_rl_apply_delay','cmf_rl_apply_delay.azd_id= cmf_rl_hise_service_project.azd_id')
                    ->where($where)
                    ->where($map)
		   
                    ->where(function($list)use($selectdata){
                        if(isset($selectdata['start_time']) && isset($selectdata['end_time'])){
                            $list->whereOr('ycgcwcsj','between',[strtotime(getMsecToMescdate($selectdata['start_time'])),strtotime(getMsecToMescdate($selectdata['end_time']))]);
                        }
                        foreach($selectdata as $k=>$v){
                            switch ($k){
                                case 'yh_name':
                                    $list->whereOr('yh_name','like','%'.$selectdata['yh_name'].'%');
                                    break;
                                case 'sj_one':
                                    $list->whereOr('sj_one','like','%'.$selectdata['sj_one'].'%');
                                    break;
                                case 'azd_id':
                                    $list->whereOr('azd_id','like','%'.$selectdata['azd_id'].'%');
                                    break;
                                case 'address':
                                    $list->whereOr('address','like','%'.$selectdata['address'].'%');
                                    break;
                                case 'jxsxsy':
                                    $list->whereOr('jxsxsy','like','%'.$selectdata['jxsxsy'].'%');
                                    break;
                                case 'jxs_mc':
                                    $jxsbm = Db::name('rl_et_customer')->where('jxs_mc','like','%'.$selectdata['jxs_mc'].'%')->column('jxsbm');
                                    $list->whereOr('jxs','in',$jxsbm);
                                    break;
                                case 'gczt':
                                    $list->whereOr('gczt',$selectdata['gczt']);
                                    break;
                                case 'sfxjbs':
                                    $list->whereOr('sfxjbs',$selectdata['sfxjbs']);
                                    break;
                                case 'is_problem':
                                    $azd_id = Db::name('rl_inspect')->where('is_problem',1)->where('inspect_status',2)->column('azd_id');
                                    $list->whereOr('azd_id','in',$azd_id);
                                    break;
                                //申请延期标识
                                case 'is_apply_delay':
                                    $list->whereOr('is_apply_delay',$selectdata['is_apply_delay']);
                                    break;
                                default:
                                    break;
                            }
                        }
                    })
                    ->order($orderwhere)
                   // ->limit($start,$limit)
                    ->select()
                    ->toArray();
		//	dump($list);die;
       //if(isset($selectdata['is_apply_off'])){
             //foreach($list as $km=>$vm){
              // $time=($vm['yqsqzq']+8) *2592000+$vm['ycgcwcsj'];//距离延期一个月的时间
              // if($time>time()){
               // unset($list[$km]);
              // }
            // }
            // $list=array_values($list);  
         //  foreach($list as $k=>$v){
           //      if(!Db::table('cmf_rl_apply_delay')->where(['azd_id'=>$v['azd_id'], 'status'=>0])->limit(1)->count()){
             //       unset($list[$k]);
               //  }
             //}
         //}
	 $list=array_values($list);
       $azd_id_strs = array_column($list,'azd_id');
       $delay = Db::table('cmf_rl_apply_delay')->where('status','=',0)->where('azd_id','in',$azd_id_strs)->select()->toArray();
       $delay_azd_id_strs = array_column($delay,'azd_id');
             foreach($list as $k=>$v){
                     if(!in_array($v['azd_id'],$delay_azd_id_strs)){
                    unset($list[$k]);
                 }
             }
            
          }
        }



        $list=array_values($list);
        $provices = Db::name('rl_hise_area')->column('sf_name','sf_code');
        $citys = Db::name('rl_hise_dq_table')->column('dq_name','dq_code');
        $qxs = Db::name('rl_hise_qx_table')->column('qx_name','qx_code');
        // 遍历格式化数据等信息
        foreach ($list as $key => $val) {
            if(isset($selectdata['is_apply_off'])) {
                if($data['type']==1){
                    //类型为分公司 删除没有审核中的安装单
                    $wait_delay=Db::name('rl_apply_delay')->where('azd_id',$val['azd_id'])->where('status',0)->count();
                    if($wait_delay<0){
                        unset($list[$key]);
                    }

                }
                $list[$key]['runtime']=date("Y-m-d",$val['ycgcwcsj']+(2592000*($val['yqsqzq']+9)));
            }
            $list[$key]['yyaz_sj'] = $val['yyaz_sj'] ? date('Y-m-d', $val['yyaz_sj']) : '';
           /* $provice = $provices[$val['provice']];
            $city = $citys[$val['city']];
            $qx = $qxs[$val['qx']];*/
            $provice=isset($provices[$val['provice']])?$provices[$val['provice']]:'';
            $city=isset($citys[$val['city']])?$citys[$val['city']]:'';
            $qx=isset($qxs[$val['qx']])?$qxs[$val['qx']]:'';
            $list[$key]['problem_num']  = Db::name('rl_inspect')->where('azd_id',$val['azd_id'])->where('is_problem',1)->where('inspect_status',2)->count();

            //查询审核表记录
            $is_apply_delay_count=Db::name('rl_apply_delay')->where('azd_id',$val['azd_id'])->where('status',1)->count();
            $apply_delay_count=Db::name('rl_apply_delay')->where('azd_id',$val['azd_id'])->where('status',0)->count();
            if($is_apply_delay_count>0){
                $list[$key]['again_delay']=1;
            }else{
                $list[$key]['again_delay']=0;
            }
            if($is_apply_delay_count>0 and $is_apply_delay_count<2 and $apply_delay_count==0){
                 $list[$key]['is_apply_delay']=0;
             }
           if($apply_delay_count==1){
                  $list[$key]['yqsqzq']=0;
            }
            $list[$key]['address'] = $provice . $city . $qx . $val['address'];
            $list[$key]['gczt_name'] = $this->install_status_new[$val['gczt']];
            $list[$key]['engineer_name'] = Db::name('rl_et_azd')->where('engineer_code', $val['azd'])->value('engineer_name');
            unset($list[$key]['provice']);
            unset($list[$key]['city']);
            unset($list[$key]['qx']);
        }
        // 获取安装单状态数量
        $map['gczt'] = array('in','0,1,2,3,4');
        // 进行中
        $data['count_2'] = $this->installationMountCount($map);
        $map['gczt'] = 5;
        // 已完成
        $data['count_3'] = $this->installationMountCount($map);
        // 安装队列表
        $data['list'] = $list;
        // 数据返回
        $this->success('操作成功！', $data);
    }
     









    /**
     * 分公司--安装单列表   经销商编码查询
     * @api http://xxxx.com/api/department/company/installlist get
     * @param int    sfwc      2进行中 3已完成
     * @param int type 1分公司 2经销商
     *
     */
    public function installlist(){
        // 验证的规则
        $rule = [
            'sfwc' => 'require',
            'type' => 'require',
        ];
        // 错误的消息
        $msg = [
            'sfwc.require' => '安装单状态不存在',
            'type.require' => '类型不存在',
        ];
        // 获取的数据
        $data = [
            'sfwc' => $this->request->get('sfwc/d', '2'), // 获取安装单状态
            'type' => $this->request->get('type/d',1), // 类型 1分公司 2经销商
        ];
        // 直接传入验证规则
        $validate = Validate::make($rule)->message($msg);
        // 需要验证的数据
        $result = $validate->check($data);
        // 判断是否有验证错误
        if (!$result) {
            $this->error($validate->getError());
        }
        // 判断安装单状态
        if($data['sfwc'] == '2'){
            $map['gczt'] = ['in','0,1,2,3,4'];
            $map['zzdpdzt'] = 3;
        } else {
            $map['gczt'] = 5;
            $map['zzdpdzt'] = 3;
        }
        $selectdata = $this->request->param();
     
        $funt = new FunctionService;
        $selectazd = $funt->selectazd($selectdata);
        $where='';
        if(isset($selectdata['is_apply_off'])){
                $where='gczt in (3,4) and ycgcwcsj+(2592000*(yqsqzq+8)) <'.time().'  and ycgcwcsj>0';
              
        }
        //排序
        $order = $this->request->param('order','');
        $orderwhere = '';
        if($order)
        {
            if($order=='asc')
            {
                $orderwhere = 'hise_service_project_id asc';
            }
            if($order=='desc')
            {
                $orderwhere = 'hise_service_project_id desc';
            }
        }else{
    $orderwhere = 'hise_service_project_id desc';
		}
        if(!$orderwhere)
        {
            $orderwhere = 'hise_service_project_id desc';
        }
        if($data['type'] == 1){
            //分公司
            $map['fwfgs|qyfgs'] = $this->user['bm_code'];
        }elseif($data['type'] == 3){
            //根据大区获取分公司信息
            // $bm_codes = Db::table('cmf_rl_company')->where('patent_id',$this->user['bm_code'])->column('orgdept');
            // $bm_codes = implode(",", $bm_codes);
            // if(isset($selectazd['fwfgs']))
            // {
            //     $bm_codes = array_intersect($selectazd['fwfgs'],$bm_codes);
            // }
            // $map['fwfgs'] = ['in',$bm_codes];
        }else{
            //经销商
            $map['jxs'] = $this->user['bm_code'];
            $map['xsy_sj'] = $this->user['mobilphone'];
        }
        //分页
           $pege = input('param.pege');
           if($pege==null){
               $pege=1;
           }
           $limit = 10;
           if($limit==null){
               $limit=10;
           }
           $start = ($pege-1)*$limit;
       
        $field = 'azd.engineer_name,hise.yh_name,hise.fgsfwfzr,hise.azd_id,hise.address,hise.provice,hise.city,hise.qx,hise.yyaz_sj,hise.gczt,hise.jxsxsy,hise.hise_service_project_id,hise.yqsqzq,hise.is_apply_delay';
        // 获取安装单列表信息 ----- 工程列表
        if(!isset($selectdata['is_apply_off'])){
 //  dump($where);dump($map);die;
            $list = Db::table('cmf_rl_hise_service_project')
            ->where($map)
            ->where($where)
            ->where(function($list)use($selectdata,$start,$limit){
                if(isset($selectdata['start_time']) && isset($selectdata['end_time'])){

                 $list->whereOr('ycgcwcsj','between',[strtotime(getMsecToMescdate($selectdata['start_time'])),strtotime(getMsecToMescdate($selectdata['end_time']))]);
                }
             foreach($selectdata as $k=>$v){
                 switch ($k){
                     case 'yh_name':
                         $list->whereOr('yh_name','like','%'.$selectdata['yh_name'].'%');
                         break;
                     case 'azd_id':
                         $list->whereOr('azd_id','like','%'.$selectdata['azd_id'].'%');
                         break;
                     case 'sj_one':
                         $list->whereOr('sj_one','like','%'.$selectdata['sj_one'].'%');
                         break;
                     case 'address':
                         $list->whereOr('address','like','%'.$selectdata['address'].'%');
                         break;
                     case 'jxsxsy':
                         $list->whereOr('jxsxsy','like','%'.$selectdata['jxsxsy'].'%');
                         break;
                     case 'jxs_mc':
                        /* $list->whereOr('engineer_name','like','%'.$selectdata['engineer_name'].'%');*/
                         $jxsbm = Db::name('rl_et_customer')->where('jxs_mc','like','%'.$selectdata['jxs_mc'].'%')->column('jxsbm');
                         $list->whereOr('jxs','in',$jxsbm);
                         //$where['jxs'] = ['in',$jxsbm];
                         break;
                     case 'engineer_name':
                       $engineer_name = Db::name('rl_et_azd')->where('engineer_name','like','%'.$selectdata['engineer_name'].'%')->column('engineer_code');
                          $list->whereOr('azd','in',$engineer_name);
                         break;
                     case 'gczt':
                         $list->whereOr('gczt',$selectdata['gczt']);
                         break;
                     case 'sfxjbs':
                         $list->whereOr('sfxjbs',$selectdata['sfxjbs']);
                         break;
                     case 'is_problem':
                       /*  $list->whereOr('is_problem',$selectdata['is_problem']);*/
                         $azd_id = Db::name('rl_inspect')->where('is_problem',1)->where('inspect_status',2)->column('azd_id');
                         $list->whereOr('azd_id','in',$azd_id);
                         //$where['azd_id'] = ['in',$azd_id];
                         break;
                         //申请延期标识
                     case 'is_apply_delay':
                         $list->whereOr('is_apply_delay',$selectdata['is_apply_delay']);
                         break;
                     default:
                         break;
                 }
             }
            })
//->fetchSql()
            ->order($orderwhere)
            ->limit($start,$limit)
            ->select()
            ->toArray();
  // dump($orderwhere);die;
//dump($list);
        }
  if(isset($selectdata['is_apply_off'])){
             if($data['type']==1) {

                if($order=='asc')
                {
                    $orderwhere = 'hise_service_project_id asc';
                }
                if($order=='desc')
                {
                    $orderwhere = 'hise_service_project_id desc';
                }
                 //分公司
            $list=Db::table('cmf_rl_hise_service_project')
                ->alias('pro')
                ->join('cmf_rl_apply_delay delay','pro.azd_id=delay.azd_id','LEFT')
                ->where([
                    'pro.fwfgs'=>$this->user['bm_code'],
                    'delay.status'=>0,
                    'pro.gczt'=>['in','3,4']
                ])
                ->where(function($list)use($selectdata){
                    if(isset($selectdata['start_time']) && isset($selectdata['end_time'])){
                        $list->whereOr('pro.ycgcwcsj','between',[strtotime(getMsecToMescdate($selectdata['start_time'])),strtotime(getMsecToMescdate($selectdata['end_time']))]);
                    }
                    foreach($selectdata as $k=>$v){
                        switch ($k){
                            case 'yh_name' :
                                $list->whereOr('pro.yh_name','like','%'.$selectdata['yh_name'].'%');
                                break;
                            case 'sj_one':
                                $list->whereOr('pro.sj_one','like','%'.$selectdata['sj_one'].'%');
                                break;
                            //安装单号
                            case 'azd_id':
                                $list->whereOr('pro.azd_id','like','%'.$selectdata['azd_id'].'%');
                                break;
                            case 'address':
                                $list->whereOr('pro.address','like','%'.$selectdata['address'].'%');
                                break;
                            case 'jxsxsy':
                                $list->whereOr('pro.jxsxsy','like','%'.$selectdata['jxsxsy'].'%');
                                break;
			//经销商名称
                            case 'jxs_mc':
                                $jxsbm = Db::name('rl_et_customer')->where('jxs_mc','like','%'.$selectdata['jxs_mc'].'%')->column('jxsbm');
                                $list->whereOr('pro.jxs','in',$jxsbm);
                                break;
                     //分公司负责人
                            case 'fgsfwfzr':
                                  $list->whereOr('pro.fgsfwfzr','like','%'.$selectdata['fgsfwfzr'].'%');
                            break;
                            case 'gczt':
                                $list->whereOr('pro.gczt',$selectdata['gczt']);
                                break;
                            case 'sfxjbs':
                                $list->whereOr('pro.sfxjbs',$selectdata['sfxjbs']);
                                break;
                            case 'is_problem':
                                $azd_id = Db::name('rl_inspect')->where('is_problem',1)->where('inspect_status',2)->column('azd_id');
                                $list->whereOr('pro.azd_id','in',$azd_id);
                                break;
                            //申请延期标识
                            case 'is_apply_delay':
                                $list->whereOr('pro.is_apply_delay',$selectdata['is_apply_delay']);
                                break;
                            default:
                                break;
                        }
                    }
                })
                ->limit($start,$limit)
               // ->order($orderwhere)
                ->select()->toArray();








                // $list = Db::table('cmf_rl_hise_service_project')
                //     ->where($where)
                //     ->where($map)
                //     ->where(function($list)use($selectdata){
                //         if(isset($selectdata['start_time']) && isset($selectdata['end_time'])){
                //             $list->whereOr('ycgcwcsj','between',[strtotime(getMsecToMescdate($selectdata['start_time'])),strtotime(getMsecToMescdate($selectdata['end_time']))]);
                //         }
                //         foreach($selectdata as $k=>$v){
                //             switch ($k){
                //                 case 'yh_name':
                //                     $list->whereOr('yh_name','like','%'.$selectdata['yh_name'].'%');
                //                     break;
                //                 case 'sj_one':
                //                     $list->whereOr('sj_one','like','%'.$selectdata['sj_one'].'%');
                //                     break;
                //                 case 'azd_id':
                //                     $list->whereOr('azd_id','like','%'.$selectdata['azd_id'].'%');
                //                     break;
                //                 case 'address':
                //                     $list->whereOr('address','like','%'.$selectdata['address'].'%');
                //                     break;
                //                 case 'jxsxsy':
                //                     $list->whereOr('jxsxsy','like','%'.$selectdata['jxsxsy'].'%');
                //                     break;
                //                 case 'jxs_mc':
                //                     $jxsbm = Db::name('rl_et_customer')->where('jxs_mc','like','%'.$selectdata['jxs_mc'].'%')->column('jxsbm');
                //                     $list->whereOr('jxs','in',$jxsbm);
                //                     break;
                //                 case 'gczt':
                //                     $list->whereOr('gczt',$selectdata['gczt']);
                //                     break;
                //                 case 'sfxjbs':
                //                     $list->whereOr('sfxjbs',$selectdata['sfxjbs']);
                //                     break;
                //                 case 'is_problem':
                //                     $azd_id = Db::name('rl_inspect')->where('is_problem',1)->where('inspect_status',2)->column('azd_id');
                //                     $list->whereOr('azd_id','in',$azd_id);
                //                     break;
                //                 //申请延期标识
                //                 case 'is_apply_delay':
                //                     $list->whereOr('is_apply_delay',$selectdata['is_apply_delay']);
                //                     break;
                //                 default:
                //                     break;
                //             }
                //         }
                //     })
                //     ->order($orderwhere)
                //     ->select()
                //     ->toArray();
                //     $azd_id_strs = array_column($list,'azd_id');
                //     $delay = Db::table('cmf_rl_apply_delay')->where('status','=',0)->where('azd_id','in',$azd_id_strs)->select()->toArray();
                //     $delay_azd_id_strs = array_column($delay,'azd_id');
                //           foreach($list as $k=>$v){
                //                   if(!in_array($v['azd_id'],$delay_azd_id_strs)){
                //                  unset($list[$k]);
                //               }
                //           }
                     }else{
                         //经销商
                     $list = Db::table('cmf_rl_hise_service_project')
                     ->where($map)
                     ->where($where)
                     ->where(function($list)use($selectdata,$start,$limit){
        if(isset($selectdata['start_time']) && isset($selectdata['end_time'])){

         $list->whereOr('ycgcwcsj','between',[strtotime(getMsecToMescdate($selectdata['start_time'])),strtotime(getMsecToMescdate($selectdata['end_time']))]);
        }
   // if(!isset($selectdata['is_apply_off'])){
    //       $list->limit($start,$limit);
     // }
     foreach($selectdata as $k=>$v){
         switch ($k){
             case 'yh_name':
                 $list->whereOr('yh_name','like','%'.$selectdata['yh_name'].'%');
                 break;
             case 'azd_id':
                 $list->whereOr('azd_id','like','%'.$selectdata['azd_id'].'%');
                 break;
             case 'sj_one':
                 $list->whereOr('sj_one','like','%'.$selectdata['sj_one'].'%');
                 break;
             case 'address':
                 $list->whereOr('address','like','%'.$selectdata['address'].'%');
                 break;
             case 'jxsxsy':
                 $list->whereOr('jxsxsy','like','%'.$selectdata['jxsxsy'].'%');
                 break;
             case 'jxs_mc':
                /* $list->whereOr('engineer_name','like','%'.$selectdata['engineer_name'].'%');*/
                 $jxsbm = Db::name('rl_et_customer')->where('jxs_mc','like','%'.$selectdata['jxs_mc'].'%')->column('jxsbm');
                 $list->whereOr('jxs','in',$jxsbm);
                 //$where['jxs'] = ['in',$jxsbm];
                 break;
              case 'engineer_name':
                 $azd = Db::name('rl_et_azd')->where('engineer_name','like','%'.$selectdata['engineer_name'].'%')->column('engineer_code'); 
                 $list->whereOr('azd','in',$azd);
                 break;
             case 'gczt':
                 $list->whereOr('gczt',$selectdata['gczt']);
                 break;
             case 'sfxjbs':
                 $list->whereOr('sfxjbs',$selectdata['sfxjbs']);
                 break;
             case 'is_problem':
               /*  $list->whereOr('is_problem',$selectdata['is_problem']);*/
                 $azd_id = Db::name('rl_inspect')->where('is_problem',1)->where('inspect_status',2)->column('azd_id');
                 $list->whereOr('azd_id','in',$azd_id);
                 //$where['azd_id'] = ['in',$azd_id];
                 break;
                 //申请延期标识
             case 'is_apply_delay':
                 $list->whereOr('is_apply_delay',$selectdata['is_apply_delay']);
                 break;
             default:
                 break;
         }
     }
    })
    ->order($orderwhere)
    ->limit($start,$limit)
    ->select()
    ->toArray();
                     }


                }else{
                    //经销商
                     $list = Db::table('cmf_rl_hise_service_project')
                             ->where($map)
                             ->where($where)
                             ->where(function($list)use($selectdata,$start,$limit){
                if(isset($selectdata['start_time']) && isset($selectdata['end_time'])){

                 $list->whereOr('ycgcwcsj','between',[strtotime(getMsecToMescdate($selectdata['start_time'])),strtotime(getMsecToMescdate($selectdata['end_time']))]);
                }
           // if(!isset($selectdata['is_apply_off'])){
            //       $list->limit($start,$limit);
             // }
             foreach($selectdata as $k=>$v){
                 switch ($k){
                     case 'yh_name':
                         $list->whereOr('yh_name','like','%'.$selectdata['yh_name'].'%');
                         break;
                     case 'azd_id':
                         $list->whereOr('azd_id','like','%'.$selectdata['azd_id'].'%');
                         break;
                     case 'sj_one':
                         $list->whereOr('sj_one','like','%'.$selectdata['sj_one'].'%');
                         break;
                     case 'address':
                         $list->whereOr('address','like','%'.$selectdata['address'].'%');
                         break;
                     case 'jxsxsy':
                         $list->whereOr('jxsxsy','like','%'.$selectdata['jxsxsy'].'%');
                         break;
                     case 'jxs_mc':
                        /* $list->whereOr('engineer_name','like','%'.$selectdata['engineer_name'].'%');*/
                         $jxsbm = Db::name('rl_et_customer')->where('jxs_mc','like','%'.$selectdata['jxs_mc'].'%')->column('jxsbm');
                         $list->whereOr('jxs','in',$jxsbm);
                         //$where['jxs'] = ['in',$jxsbm];
                         break;
                     case 'engineer_name':
                          $azd = Db::name('rl_et_azd')->where('engineer_name','like','%'.$selectdata['engineer_name'].'%')->column('engineer_code');
                          $list->whereOr('azd','in',$azd);
                          break;
                     case 'gczt':
                         $list->whereOr('gczt',$selectdata['gczt']);
                         break;
                     case 'sfxjbs':
                         $list->whereOr('sfxjbs',$selectdata['sfxjbs']);
                         break;
                     case 'is_problem':
                       /*  $list->whereOr('is_problem',$selectdata['is_problem']);*/
                         $azd_id = Db::name('rl_inspect')->where('is_problem',1)->where('inspect_status',2)->column('azd_id');
                         $list->whereOr('azd_id','in',$azd_id);
                         //$where['azd_id'] = ['in',$azd_id];
                         break;
                         //申请延期标识
                     case 'is_apply_delay':
                         $list->whereOr('is_apply_delay',$selectdata['is_apply_delay']);
                         break;
                     default:
                         break;
                 }
             }
            })
            ->order($orderwhere)
            ->limit($start,$limit)
            ->select()
            ->toArray();
            }
        $list=array_values($list);
        $provices = Db::name('rl_hise_area')->column('sf_name','sf_code');
        $citys = Db::name('rl_hise_dq_table')->column('dq_name','dq_code');
        $qxs = Db::name('rl_hise_qx_table')->column('qx_name','qx_code');
        // 遍历格式化数据等信息
        foreach ($list as $key => $val) {
            if(isset($selectdata['is_apply_off'])) {
                if($data['type']==1){
                    //类型为分公司 删除没有审核中的安装单
                    $wait_delay=Db::name('rl_apply_delay')->where('azd_id',$val['azd_id'])->where('status',0)->count();
                    if($wait_delay<0){
                        unset($list[$key]);
                    }

                }
                //$list[$key]['runtime']=date("Y-m-d",$val['ycgcwcsj']+(2592000*($val['yqsqzq']+9)));
                 $list[$key]['runtime']=date('Y-m-d ',strtotime("+".($val['yqsqzq']+9)." month",$val['ycgcwcsj']));
            }
            $list[$key]['yyaz_sj'] = $val['yyaz_sj'] ? date('Y-m-d', $val['yyaz_sj']) : '';
           /* $provice = $provices[$val['provice']];
            $city = $citys[$val['city']];
            $qx = $qxs[$val['qx']];*/
            $provice=isset($provices[$val['provice']])?$provices[$val['provice']]:'';
            $city=isset($citys[$val['city']])?$citys[$val['city']]:'';
            $qx=isset($qxs[$val['qx']])?$qxs[$val['qx']]:'';
            $list[$key]['problem_num']  = Db::name('rl_inspect')->where('azd_id',$val['azd_id'])->where('is_problem',1)->where('inspect_status',2)->count();

            //查询审核表记录
          //  $is_apply_delay_count=Db::name('rl_apply_delay')->where('azd_id',$val['azd_id'])->where('status',1)->count();
           // $apply_delay_count=Db::name('rl_apply_delay')->where('azd_id',$val['azd_id'])->where('status',0)->count();
            



		//查询审核表记录
            //已审核数量
            $is_apply_delay_count=Db::name('rl_apply_delay')->where('azd_id',$val['azd_id'])->where('status',1)->count();
            $no_apply_delay_count=Db::name('rl_apply_delay')->where('azd_id',$val['azd_id'])->where('status',2)->count();
            //未审核数量
            $apply_delay_count=Db::name('rl_apply_delay')->where('azd_id',$val['azd_id'])->where('status',0)->count();
            //if($is_apply_delay_count>0){
              //  $list[$key]['again_delay']=1;
           // }else{
             //   $list[$key]['again_delay']=0;
           // }
            if($data['type'] == 1){
                //分公司
                //首次审核
                if( $is_apply_delay_count==0 and $apply_delay_count==1){
                    //首次提交未审核
                    $list[$key]['again_delay']=0;
                }
                if($is_apply_delay_count==1 and $apply_delay_count==0){
                    //首次提交审核通过
                    $list[$key]['again_delay']=1;
                }
                //二次审核
                if($is_apply_delay_count==1 and $apply_delay_count==1){
                    //二次已提交未审核
                    $list[$key]['again_delay']=2;
                }
                if($is_apply_delay_count>1){
                    //二次审核完成
                    $list[$key]['again_delay']=3;
                }
                if($no_apply_delay_count==1 and $apply_delay_count==0){
                    //一次审核不通过
                    $list[$key]['again_delay']=9;
                }
                if($no_apply_delay_count==2 and $is_apply_delay_count>0){
                    //二次审核不通过
                    $list[$key]['again_delay']=10;
                }
            }else{
                //经销商
                //首次审核
                if( $is_apply_delay_count==0 and $apply_delay_count==0){
                    //首次未提交
                    $list[$key]['again_delay']=4;
                }
                if( $is_apply_delay_count==0 and $apply_delay_count==1){
                    //首次提交未审核
                    $list[$key]['again_delay']=5;
                }
                if( $is_apply_delay_count==1 and $apply_delay_count==0){
                     //首次提交审核通过
                    $list[$key]['again_delay']=6;
                }
                 //二次审核
   
                 if($is_apply_delay_count==1 and $apply_delay_count==1){
                    //二次已提交未审核
                    $list[$key]['again_delay']=7;
                }
                if($is_apply_delay_count>1){
                    //二次审核完成
                    $list[$key]['again_delay']=8;
                }
                if($no_apply_delay_count==1 and $apply_delay_count==0){
                    //一次审核不通过
                    $list[$key]['again_delay']=9;
                }
                if($no_apply_delay_count==2 and $is_apply_delay_count>0){
                    //二次审核不通过
                    $list[$key]['again_delay']=10;
                }
            }



		//if($is_apply_delay_count>0){
                //$list[$key]['again_delay']=1;
           // }else{
             //   $list[$key]['again_delay']=0;
           // }
            if($is_apply_delay_count>0 and $is_apply_delay_count<2 and $apply_delay_count==0){
                 $list[$key]['is_apply_delay']=0;
             }
           if($apply_delay_count==1){
                  $list[$key]['yqsqzq']=0;
            }
            $list[$key]['address'] = $provice . $city . $qx . $val['address'];
            $list[$key]['gczt_name'] = $this->install_status_new[$val['gczt']];
            $list[$key]['engineer_name'] = Db::name('rl_et_azd')->where('engineer_code', $val['azd'])->value('engineer_name');
            unset($list[$key]['provice']);
            unset($list[$key]['city']);
            unset($list[$key]['qx']);
        }
        // 获取安装单状态数量
        $map['gczt'] = array('in','0,1,2,3,4');
        // 进行中
        $data['count_2'] = $this->installationMountCount($map);
        $map['gczt'] = 5;
        // 已完成
        $data['count_3'] = $this->installationMountCount($map);
        // 安装队列表
        $data['list'] = $list;
        // 数据返回
        $this->success('操作成功！', $data);
    }




}
